import { RESIZING, CENTER, TOP, BOTTOM } from '/node_modules/fabric/src/constants'
import { resolveOrigin } from '/node_modules/fabric/src/util/misc/resolveOrigin'
import { getLocalPoint, isTransformCentered } from '/node_modules/fabric/src/controls/util'
import { wrapWithFireEvent } from '/node_modules/fabric/src/controls/wrapWithFireEvent'
import { wrapWithFixedAnchor } from '/node_modules/fabric/src/controls/wrapWithFixedAnchor'

/**
 * Action handler to change object's height
 * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
 * @param {Event} eventData javascript event that is doing the transform
 * @param {Object} transform javascript object containing a series of information around the current transform
 * @param {number} x current mouse x position, canvas normalized
 * @param {number} y current mouse y position, canvas normalized
 * @return {Boolean} true if some change happened
 */
const changeObjectHeight = (eventData, transform, x, y) => {
  const localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y)
  // 仅在控制点对应的一侧拖拽时生效
  if (
    resolveOrigin(transform.originY) === resolveOrigin(CENTER) ||
    (resolveOrigin(transform.originY) === resolveOrigin(BOTTOM) && localPoint.y < 0) ||
    (resolveOrigin(transform.originY) === resolveOrigin(TOP) && localPoint.y > 0)
  ) {
    const { target } = transform
    const strokePadding = target.strokeWidth / (target.strokeUniform ? target.scaleY : 1)
    const multiplier = isTransformCentered(transform) ? 2 : 1
    const oldHeight = target.height
    const newHeight = Math.ceil(
      Math.abs((localPoint.y * multiplier) / target.scaleY) - strokePadding,
    )
    target.set('height', Math.max(newHeight, 0))
    return oldHeight !== target.height
  }
  return false
}
export const changeHeight = wrapWithFireEvent(RESIZING, wrapWithFixedAnchor(changeObjectHeight))
